<template>
  <div class="app-container">
    <div class="search-container">
      <el-form :model="searchParam" :inline="true" label-width="70px">
        <el-form-item label="工厂">
          <el-select
            v-model="searchParam.plantId"
            placeholder="请选择所在工厂"
            clearable
            @change="changePlant(searchParam.plantId)"
          >
            <el-option
              v-for="item in plantList"
              :key="item.id"
              :label="item.organizationCode"
              :value="item.id"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="工作中心">
          <el-select
            v-model="searchParam.workCenterId"
            placeholder="请选择工作中心"
            clearable
            :disabled="searchParam.plantId == ''"
          >
            <el-option
              v-for="item in workCenterValue"
              :key="item.id"
              :label="`${item.workshopCode}-${item.workshopName}`"
              :value="item.id"
            />
          </el-select>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="search">
            <i-ep-search />
            搜索
          </el-button>
          <el-button @click="reset">
            <i-ep-refresh />
            重置
          </el-button>
        </el-form-item>
      </el-form>
    </div>

    <el-card shadow="never" class="table-container">
      <template #header>
        <el-button
          type="primary"
          :disabled="ids.length === 0"
          @click="handleTableReceive()"
          >批量收货
        </el-button>
      </template>

      <el-table
        ref="dataTableRef"
        v-loading="loading"
        :data="tableData"
        highlight-current-row
        border
        @selection-change="handleSelectionChange"
        :header-cell-style="{ textAlign: 'center' }"
      >
        <el-table-column type="selection" width="55" align="center" />
        <el-table-column
          type="index"
          label="序号"
          width="70"
          key="id"
          align="center"
        />
        <el-table-column
          label="工厂"
          prop="plantCode"
          width="100"
          show-overflow-tooltip
        />
        <el-table-column
          label="工作中心"
          prop="workCenterCode"
          min-width="100"
          show-overflow-tooltip
        />
        <el-table-column
          label="物料"
          prop="materialCode"
          min-width="160"
          show-overflow-tooltip
        >
          <template #default="scope">
            {{ scope.row.materialCode }} - {{ scope.row.materialName }}
          </template>
        </el-table-column>
        <el-table-column
          label="物料批次"
          prop="materialBatch"
          min-width="100"
          show-overflow-tooltip
        />
        <el-table-column
          label="要货记录编码"
          prop="requestCode"
          min-width="160"
          show-overflow-tooltip
        />

        <el-table-column
          label="要货数量"
          prop="requestQuantity"
          min-width="100"
          show-overflow-tooltip
          align="right"
        />
        <el-table-column
          label="送货物料条码"
          prop="arriveBarcode"
          min-width="100"
          show-overflow-tooltip
        />

        <el-table-column
          label="送达数量"
          prop="arriveQuantity"
          min-width="100"
          show-overflow-tooltip
          align="right"
        />
        <el-table-column
          label="数量单位"
          prop="quantityUnit"
          min-width="100"
          align="center"
        >
          <template #default="scope">
            {{ useDictionary("MeasurementUnit", scope.row.quantityUnit) }}
          </template>
        </el-table-column>
        <el-table-column
          label="送达时间"
          prop="arriveTime"
          min-width="120"
          show-overflow-tooltip
          align="center"
        />
        <el-table-column fixed="right" label="操作" width="80" align="center">
          <template #default="scope">
            <el-button
              type="primary"
              size="small"
              link
              @click="handleTableReceive(scope.row.id)"
              >收货
            </el-button>
          </template>
        </el-table-column>
      </el-table>

      <el-pagination
        :background="true"
        :current-page="pageable.pageNum"
        :page-size="pageable.pageSize"
        :page-sizes="[10, 25, 50, 100]"
        :total="pageable.total"
        layout="total, sizes, prev, pager, next, jumper"
        class="mt-[20px]"
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
      />
    </el-card>

    <mesmaterialrequest-edit
      :visible="addDialog.visible"
      :title="addDialog.title"
      :data="addDialog.data"
      @reset-table="(id:string) => (id?.length ? getTableList() : reset())"
      :is-readonly="addDialog.readvisible"
      @change-visible="changeVisible"
    />
  </div>
</template>

<script setup lang="ts">
import { useTable, useDownload, useDictionary } from "@/utils/useTable";
import request from "@/utils/request";

defineOptions({
  name: "MESMESMATERIALREQUEST",
  inheritAttrs: false,
});

// 请求参数
const requestApi = "/mes/mesmaterialrequest/queryByPage";

// 是否需要分页
const pagination = true;

const initParam = {};

// 初始化搜索参数数据
const searchParamInit = {
  plantId: "",
  workCenterId: "",
  isArrive: 1,
  isReceive: 0,
};

const deleteParam = {
  api: "/mes/mesmaterialrequest/delete",
  data: {},
};

// 数据请求错误后处理
function requestError() {}

const dataCallBack = ref(undefined); // 无需二次数据处理&不传赞数也行

// 表格操作 Hooks
const {
  tableData,
  pageable,
  searchParam,
  ids,
  getTableList,
  search,
  reset,
  handleSizeChange,
  handleCurrentChange,
  handleSelectionChange,
  handleTableDelete,
  loading,
}: any = useTable(
  requestApi,
  initParam,
  searchParamInit,
  pagination,
  dataCallBack.value,
  requestError,
  deleteParam
);

onMounted(() => {
  getTableList();
});

const addDialog = reactive<DialogOption>({
  visible: false,
  readvisible: false,
  title: "",
  data: {},
});

// 查询详情
async function getInfo(id: string) {
  request({
    url: `/mes/mesmaterialrequest/get/${id}`,
    method: "get",
  })
    .then((data) => {
      addDialog.data = data.data;
      addDialog.visible = true;
    })
    .catch((res) => {
      console.log(res);
    });
}

/** 打开缺料要货表单弹窗 */
function openDialog(roleObj?: Object) {
  if (roleObj) {
    addDialog.title = "修改缺料要货";
    getInfo(roleObj.id);
  } else {
    addDialog.title = "新增缺料要货";
    addDialog.visible = true;
  }
  addDialog.readvisible = false;
}

/** 打开缺料要货表单弹窗 详情 */
function openDialogdetail(roleObj?: any) {
  addDialog.title = "缺料要货详情";
  getInfo(roleObj.id);
  addDialog.readvisible = true;
}

function changeVisible(value: boolean) {
  addDialog.visible = value;
  if (!value) {
    addDialog.data = {};
  }
}

// 获取工厂列表
const plantList: any = ref([]);
const getPlantList = async () => {
  const res1 = await request({
    url: "system/sysOrganization/getList",
    method: "post",
    data: { organizationType: 3 },
  });
  plantList.value = res1.data;
  searchParam.value.plantId = plantList.value[0].id;
  changePlant(searchParam.plantId);
};
// 根据工厂id 查询中心
const workCenterValue: any = ref([]);
const workCenterList = async (id) => {
  if (id != "") {
    const res2: any = await request({
      url: `/mes/mesworkshop/getList`,
      method: "post",
      data: { enabled: 1, plantId: id },
    });
    workCenterValue.value = res2.data;
  } else {
    workCenterValue.value = [];
  }
};
/** 选择工厂时触发 根据Code赋值Id*/

const changePlant = (id) => {
  workCenterValue.value = [];
  workCenterList(id);
};
onMounted(() => {
  getPlantList();
});
//批量收货
const handleTableReceive = async (id?: string) => {
  if (id) {
    ids.value = [id];
  }
  ElMessageBox.confirm("确认对已选中的数据项进行收货吗?", "提示", {
    confirmButtonText: "确认",
    cancelButtonText: "取消",
    type: "warning",
  }).then(async () => {
    const res: any = await request({
      url: "/mes/mesmaterialrequest/receive",
      method: "post",
      data: { ids: ids.value },
    });
    if (res.code == 200) {
      ElMessage({
        type: "success",
        message: "批量收货成功",
      });
    }
    getTableList();
  });
};
</script>
